from flask import *
from src.day12.work.userModel import User

user = Blueprint("user", __name__, url_prefix="/user")


def get_error_response(data, msg):
    return make_response(jsonify(code=1, data=data, msg=msg))


def get_success_response(data, msg):
    return make_response(jsonify(code=0, data=data, msg=msg))


users: list[User]
users = [User("tom", 12, 1)]
user_id: int = 0


def generate_user_id():
    global user_id
    user_id += 1
    return user_id


def is_user_id_Exist(id):
    for u in users:
        if u.id == id:
            return u
    return False


@user.route("/list/<int:id>", methods=["Get"])
def get_user(id: int):
    if u := is_user_id_Exist(id):
        return get_success_response(str(u), f"查询id：{id},成功")
    return get_error_response({}, f"查询id：{id},失败")


@user.route("/list/all", methods=["Get"])
def get_user_all():
    data = [str(u) for u in users]

    return get_success_response(data, f"成功")


@user.route("delete/<int:id>", methods=["Get"])
def del_user(id: int):
    del_obj = None
    for u in users:
        if u.id == id:
            del_obj = u
            break
    if del_obj is None:
        return get_error_response(data="", msg=f"删除id：{id},失败")
    else:
        return get_success_response(data="", msg=f"删除id：{id},成功")


@user.route("/add", methods=["POST"])
def add_user():
    name = request.values.get("name")
    age = request.values.get("age")
    if name and age:
        u = User(name=name, age=age, id=generate_user_id())
        users.append(u)
        return get_success_response(data="", msg=f"添加用户成功")
    else:
        return get_error_response(data="", msg="添加用户失败")


@user.route("/set", methods=["POST"])
def update_user():
    name = request.values.get("name")
    age = request.values.get("age")
    id = request.values.get("id")
    id = int(id)
    for u in users:
        if id == u.id:
            u.name = name
            u.age = age
            return get_success_response(data={}, msg="更新成功")
    return get_error_response(data={}, msg=f"没有id={id}")
